<template>
  <div id="forgot-password-page" class="forgot-password-container">
    <div>
      <h1>重置密码</h1>
    </div>
    <el-form
        :model="forgotPasswordForm"
        :rules="forgotPasswordRules"
        label-position="top"
        label-width="150px"
        ref="forgotPasswordFormRef"
        class="forgot-password-form"
    >
      <el-form-item label="邮箱" prop="userEmail">
        <el-input
            v-model="forgotPasswordForm.userEmail"
            placeholder="请输入邮箱地址"
            class="input-field"
        />
      </el-form-item>


      <el-form-item label="新密码" prop="newPassword">
        <el-input
            v-model="forgotPasswordForm.newPassword"
            placeholder="请输入新密码"
            show-password
            class="input-field"
        />
      </el-form-item>

      <el-form-item label="确认新密码" prop="confirmPassword">
        <el-input
            v-model="forgotPasswordForm.confirmPassword"
            placeholder="请再次输入新密码"
            show-password
            class="input-field"
        />
      </el-form-item>
      <el-form-item class="verification-container">
        <el-input
            v-model="forgotPasswordForm.verificationCode"
            placeholder="请输入验证码"
            class="verification-input"
        />
        <span
            class="send-verification-code"
            @click="sendVerificationCode"
            :class="{ disabled: isCodeSent }"
        >
          {{ isCodeSent ? '验证码已发送' : '获取验证码' }}
        </span>
      </el-form-item>

      <el-form-item class="action-buttons">
        <el-button type="primary" @click="resetPassword" class="reset-button">重置密码</el-button>
        <router-link to="login" class="back-to-login-link">返回登录</router-link>
      </el-form-item>
    </el-form>
  </div>
</template>

<script lang="ts" setup>
import {reactive, ref} from "vue";
import { axiosInstance } from "@/axios";
import { ElMessage } from "element-plus";
import { useRouter ,useRoute} from "vue-router";

const router = useRouter();
const route=useRoute();


const forgotPasswordForm = reactive({
  userEmail: '',
  verificationCode: '',
  newPassword: '',
  confirmPassword: ''
});

const forgotPasswordRules = {
  userEmail: [
    { required: true, message: "请输入邮箱地址", trigger: "blur" },
    { type: "email", message: "请输入正确的邮箱地址", trigger: ["blur", "change"] }
  ],
  verificationCode: [
    { required: true, message: "请输入验证码", trigger: "blur" }
  ],
  newPassword: [
    { required: true, message: "请输入新密码", trigger: "blur" }
  ],
  confirmPassword: [
    { required: true, message: "请再次输入新密码", trigger: "blur" },
    {
      validator: (rule, value, callback) => {
        if (value !== forgotPasswordForm.newPassword) {
          callback(new Error("两次输入的密码不一致"));
        } else {
          callback();
        }
      },
      trigger: "blur"
    }
  ]
};

const forgotPasswordFormRef = ref();
const isCodeSent = ref(false);

const sendVerificationCode = () => {
  if (isCodeSent.value) return;

  // 校验邮箱格式
  forgotPasswordFormRef.value.validateField('userEmail', (valid) => {
    if (valid) {
      axiosInstance.get('/user/sendForgetPasswordEmailCode?userEmail=' + forgotPasswordForm.userEmail)
          .then(response => {
            if (response.data.code === 100000) {
              ElMessage({
                message: response.data.message,
                type: "success",
              });
              isCodeSent.value = true;
            } else {
              ElMessage({
                message: response.data.message,
                type: "error"
              });
            }
          })
          .catch(() => {
            ElMessage({
              message: "发送验证码失败",
              type: "error",
            });
          });
    }
  });
};

const resetPassword = () => {
  forgotPasswordFormRef.value.validate((valid: boolean) => {
    if (valid) {
      const forgetPasswordUser = {

            userEmail: forgotPasswordForm.userEmail,
            userPassword: forgotPasswordForm.newPassword,
            emailCode:forgotPasswordForm.verificationCode
      };

      axiosInstance.post('/user/forgetPassword', forgetPasswordUser)
          .then(response => {
            if (response.data.code === 100000) {
              ElMessage({
                message: response.data.message,
                type: "success",
              });
              router.push({ path: '/user/login', query: { userEmail: forgotPasswordForm.userEmail } });
            } else {
              ElMessage({
                message: response.data.message,
                type: "error"
              });
            }
          })
          .catch(error => {
            ElMessage({
              message: error.message,
              type: "error"
            });
          });
    }
  });
};
</script>

<style scoped>
.forgot-password-container {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  height: 100vh;
  padding: 20px;
  background-color: #f0f2f5;
}

.forgot-password-form {
  width: 450px;
  max-width: 90%;
  padding: 30px;
  border-radius: 8px;
  background-color: #fff;
}

.input-field {
  width: 100%;
  height: 45px;
}

.verification-container {
  display: flex;
  align-items: center;
}

.verification-input {
  flex: 1;
  height: 45px;
}

.send-verification-code {
  margin-left: 10px;
  cursor: pointer;
  color: #549f53;
}

.send-verification-code.disabled {
  color: gray;
  cursor: not-allowed;
}

.action-buttons {
  display: flex;
  justify-content: center;
  align-items: center;
}

.reset-button {
  width: 200px;
  height: 45px;
  font-size: 18px;
  margin-right: 10px; /* 添加间距 */
}

.back-to-login-link {
  font-size: 16px;
  color: #05a0c9;
  margin-left: 50px;
  cursor: pointer;
}

.back-to-login-link:hover {
  color: #66b1ff;
}

</style>
